import { nanoid } from "nanoid";
import {
  isArray,
  isNull,
  isNumber,
  isObject,
  isString,
  isUndefined,
  isVirtualDOM,
} from "./types";

const proxyKey = (object: { [x: string]: any; diff_value?: any }) => {
  const key = "diff_key";
  Object.defineProperty(object, key, {
    value: object[key] ? object[key] : nanoid(8),
    writable: false,
    enumerable: false,
    configurable: false,
  });
  return object;
};
export const addKey = (array: any[]) => {
  return array.map((item) => {
    if (isString(item) || isNumber(item) || isNull(item) || isUndefined(item)) {
      const object = {
        diff_value: item,
      };
      return proxyKey(object);
    }
    if (isVirtualDOM(item)) return item;
    if (isObject(item)) proxyKey(item);
    return item;
  });
};
export const deepAddKey = (object: any) => {
  if (!isObject(object) && !isArray(object)) return object;
  for (const key in object) {
    const value = object[key];
    if (isVirtualDOM(value)) continue;
    if (isObject(value)) {
      const result = proxyKey(value);
      deepAddKey(result);
    }
    if (isArray(value)) deepAddKey(value);
  }
  return object;
};
